/**
 * Description: 服务端
 * File: server.c |Time: 2021-07-11 09:44
 */

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <string.h>
#include "trans.h"


int main(int argc, const char *argv[])
{
    if (argc < 3) 
    {
        printf("Usage: %s <ip> <port>", argv[0]);
    }

    int ret = 0;
    int acceptfd;
    msg_t msg;
    int sock_tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_tcp_fd < 0) 
    {
        ERR("socket");
    }

    // UDP socket
    int sock_udp_fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in server_addr;
    socklen_t addrlen = sizeof(server_addr);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[2]));
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);

    ret = bind(sock_tcp_fd, (struct sockaddr *)&server_addr, addrlen);
    if (ret < 0) 
    {
        ERR("bind");
    }

    // 绑定UDP
    ret = bind(sock_udp_fd, (struct sockaddr *)&server_addr, addrlen);
    if (ret < 0) 
    {
        ERR("bind");
    }

    ret = listen(sock_tcp_fd, 10);
    if (ret < 0) 
    {
        ERR("bind");
    }

    pid_t pid = fork();
    if (pid < 0) 
    {
        ERR("fork");
    }

    if (pid == 0) 
    {
        acceptfd = accept(sock_tcp_fd, (struct sockaddr *)&server_addr, &addrlen);
        if (acceptfd < 0) {
            ERR("accept");
        }

        while(1) {
            memset(&msg, 0, sizeof(msg));
            ret = recv(acceptfd, &msg, sizeof(msg_t), 0);
            if (ret < 0) 
            {
                ERR("recv");
            }

            if (ret == 0) 
            {
                printf("client disconnected.\n");
                break;
            }

            printf("[tcp recv msg] %s\n", msg.msg);
  
        }    
    } else {
        while(1) {
            memset(&msg, 0, sizeof(msg));

            // UDP receive
            memset(&msg, 0, sizeof(msg));
            ret = recvfrom(sock_udp_fd, &msg, sizeof(msg_t), 0, NULL, NULL);
            if (ret < 0) 
            {
                ERR("recvfrom");
            }

            printf("[udp recv msg] %s\n", msg.msg);
        }
    }
    
    
    ret = close(sock_tcp_fd);
    if (ret < 0) 
    {
        ERR("close");
    }
    
    return 0;
}

